package com.zlf.sb.demo.completableFuture;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.function.Predicate;

public class WorkflowBuilder<T> {
    private final List<WorkflowStage<T, ?>> stages = new ArrayList<>();

    public <R> WorkflowBuilder<T> addStage(Function<T, CompletableFuture<R>> operation, Predicate<T> condition, Function<T, R> fallback) {
        stages.add(new WorkflowStage<>(operation, condition, fallback));
        return this;
    }

    public CompletableFuture<T> build(T initialInput) {
        CompletableFuture<T> workflowResult = CompletableFuture.completedFuture(initialInput);
        for (WorkflowStage<T, ?> stage : stages) {
            workflowResult = (CompletableFuture<T>) workflowResult.thenCompose(input -> stage.execute(input));
        }
        return workflowResult;
    }
}
